/**
 * 服务器监听js
 */
// 一个ws 表示一个通讯管道
var webSocketUrl=basePath.replace("http","ws")+"/websocket";

var EXWebSocket=function(){
	
	"use strict";// 严格模式
	var _this = null;
	
	return{
		
		webSocket:{},// websocket对象
		//开启链接
		connectWebSocket :function(msg) {
			
			_this=this;
			
			if ('WebSocket' in window) {
				_this.webSocket = new WebSocket(webSocketUrl);
			} else if ('MozWebSocket' in window) {
				_this.webSocket = new MozWebSocket(webSocketUrl);
			} else {
				alert('WebSocket is not supported by this browser.');
				return;
			}

			_this.webSocket.onerror = function(event) {
				_this.onError(event)
			};

			_this.webSocket.onopen = function(event) {
				document.getElementById('serviceMessage').innerHTML = '管道已连接。。。。';
				// 连接后发送登陆请求
				_this.sendMessage(msg);
			};

			_this.webSocket.onmessage = function(event) {
				_this.onMessage(event)
			};
			return _this;
		},

		// 发送消息
		sendMessage : function (msg) {
			var str=JSON.stringify(msg);
			_this.webSocket.send(str);
		},
		
		/**
		 * 处理服务断事件
		 * 
		 * @param event
		 */
		onMessage:function (event) {
			
			var action= JSON.parse(event.data);
			// 登陆返回状态
			if(action.type=='loginReturn'){
				if(action.value!='success'){
					layer.msg("后台通讯协议登陆失败！");
				}
			// 新订单来啦
			}else if(action.type=='newOrder'){
					layer.alert(action.value+"您有新的订单请及时处理");
					_this.playSound(basePath+"/plat/video/neworder.ogg");
			}
			console.log(event.data);
		},

		playSound:function (src){
			var sound =document.getElementById("backgroundsound");
			sound.src=src;
			sound.autoplay=true;
		},


		onError:function (event) {
			alert(event.data);
		},
		/**
		 * 打开接收订单标记
		 */
		acceptOrderOpen:function (){
			var acceptBtn=$("#acceptOrderBtn");
			acceptBtn.removeClass("btn-success").addClass("btn-danger").unbind( "click" ).click(_this.acceptOrderClose);
			acceptBtn.find("span").html('暂停接单');
		},
		/**
		 * 关闭接收订单标记
		 */
		acceptOrderClose:function (){
			var acceptBtn=$("#acceptOrderBtn");
			acceptBtn.removeClass("btn-danger").addClass("btn-success").unbind( "click" ).click(_this.acceptOrderOpen);
			acceptBtn.find("span").html('开始接单');
		}
		
	}
}();















